package servlet;

import domain.Comments;
import org.apache.commons.beanutils.BeanUtils;
import services.CommentsServicesImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class CommentsServlet extends HttpServlet {
    CommentsServicesImpl commentsServices = new CommentsServicesImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("utf-8");
            //1.获取method名
            String method = request.getParameter("method");
            if (method.equals("addComment")) {//添加评论
                Map parameterMap = request.getParameterMap();
                //封装comment对象
                Comments comment = new Comments();
                BeanUtils.populate(comment, parameterMap);
                //添加时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = sdf.format(new Date());
                comment.setCdate(date);
                //进入服务层添加评论到数据库
                int count = commentsServices.addComments(comment);
                System.out.println("有" + count + "条评论被添加:" + comment);
                response.sendRedirect(request.getContextPath() + "/newsServlet?method=readNews&nid=" + comment.getCnid());
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
